package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.lang.model.element.VariableElement;

@RestController
@RequestMapping("/spit")
public class SpitController {

    @Autowired
    private SpitService spitService;
    @Autowired
    private RedisTemplate redisTemplate;

    //增加吐槽
    @RequestMapping(method = RequestMethod.POST)
    public Result save(@RequestBody Spit spit) {
        spitService.save(spit);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    //查询Spit全部列表
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(true, StatusCode.OK, "查询成功", spitService.findAll());
    }

    //根据ID查询吐槽
    @RequestMapping(value = "/{spitId}", method = RequestMethod.GET)
    public Result findById(@PathVariable String spitId) {
        return new Result(true, StatusCode.OK, "查询成功", spitService.findById(spitId));
    }

    //修改吐槽
    @RequestMapping(value = "/{spitId}", method = RequestMethod.PUT)
    public Result update(@PathVariable String spitId, @RequestBody Spit spit) {
        spitService.update(spitId, spit);
        return new Result(true, StatusCode.OK, "修改成功");
    }


    //根据ID删除吐槽

    @RequestMapping(value = "/{spitId}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String spitId) {
        spitService.delete(spitId);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    //分页查询回复
    @RequestMapping(value = "/comment/{parentid}/{page}/{size}", method = RequestMethod.GET)
    public Result findPage(@PathVariable String parentid, @PathVariable Integer page, @PathVariable Integer size) {
        Page<Spit> spitPage = spitService.findByParentId(parentid, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<Spit>(spitPage.getTotalElements(), spitPage.getContent()));
    }

    @RequestMapping(value = "/thumbup/{spitId}", method = RequestMethod.PUT)
    public Result thumbup(@PathVariable String spitId) {
        //获取当前用户ID
        String userId = "666";
        //从redis判断当前用户是否以为该吐槽点赞   userId_spitId  用户_吐槽(用户点赞该吐槽)
        String flag = (String) redisTemplate.opsForValue().get("thumbup_" + userId + "_" + spitId);
        if ("1".equals(flag)) {
            //点过 => 返回错误信息
            return new Result(false, StatusCode.REMOTEERROR, "请不要重复点赞");
        } else {
            //未点过调用Service点赞
            spitService.thumbup(spitId);
            //将点赞记录存入redis
            redisTemplate.opsForValue().set("thumbup_" + userId + "_" + spitId, "1");

            return new Result(true, StatusCode.OK, "点赞成功");

        }
    }


}
